package com.py.credit.service.impl;

import com.py.credit.dao.LhjcAjbhDao;
import com.py.credit.dao.OfficeDao;
import com.py.credit.dao.SyslogDao;
import com.py.credit.entity.*;
import com.py.credit.service.LhjcAjbhService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.utils.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class LhjcAjbhServiceImpl implements LhjcAjbhService {

    @Autowired
    private LhjcAjbhDao lhjcAjbhDao;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private SyslogDao syslogDao;

    @Autowired
    private OfficeDao officeDao;

    @Override
    public boolean detailIsExistOtherStorage(String jclb, String type, String ztmc, String bm) {
        if (jclb.equals("C")) {
            jclb = "J";
        } else {
            jclb = "C";
        }

        int detailIsExistOtherStorage = lhjcAjbhDao.detailIsExistOtherStorage(jclb, type, ztmc, bm);
        if (detailIsExistOtherStorage > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Date selectJzrqDate(String jclb, String qymc, String bm, String gzbm, String ysajh) {
        return lhjcAjbhDao.selectJzrqDate(jclb, qymc, bm, gzbm, ysajh);
    }

    @Override
    public void addFr(GzObj gzObj, String jclb, String tybm, String qymc, String tyshxydm, String zzjgdm, String gsdjm, String cfqx, Date date, long managerId, long deptId, String ysajh, String jdToken, SysUser userInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //不存在的企业录入到企业库
        if (lhjcAjbhDao.selectCompanyIsExist(tybm) < 1) {
            lhjcAjbhDao.addCompany(tybm, qymc, tyshxydm, zzjgdm, gsdjm);
        }

        String ajbh = this.getAjbh(gzObj.getDeptCode(), date);
        lhjcAjbhDao.addMess(tybm, "N", cfqx, "C", jclb, ajbh, gzObj.getId(), gzObj.getName(), sdf.format(date), qymc, "", tyshxydm, "M", managerId, deptId, ysajh, sdf.format(date));
        syslogDao.addProcess(ajbh, "A" + jclb, "Y", userInfo.getUsername(), userInfo.getRealName(), userInfo.getId(), userInfo.getOfficeId());
        this.addMessagecenter(gzObj.getId(), ajbh, managerId, deptId, jdToken, jclb, userInfo.getRealName(), qymc, tyshxydm, sdf.format(date), cfqx, "C", "J", gzObj.getCfbm(), gzObj.getName(), "否");
    }

    @Override
    public void addZrr(GzObj gzObj, String jclb, String tybm, String xm, String bm, String cfqx, Date date, long managerId, long deptId, String ysajh, String jdToken, SysUser userInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //不存在的企业录入到自然人库
        if (lhjcAjbhDao.selectPersonIsExist(tybm, null) < 1) {
            lhjcAjbhDao.addPerson(tybm, xm, bm, null, "S");
        }

        String ajbh = this.getAjbh(gzObj.getDeptCode(), date);
        lhjcAjbhDao.addMess(tybm, "N", cfqx, "P", jclb, ajbh, gzObj.getId(), gzObj.getName(), sdf.format(date), xm, "", bm, "M", managerId, deptId, ysajh, sdf.format(date));
        syslogDao.addProcess(ajbh, "A" + jclb, "Y", userInfo.getUsername(), userInfo.getRealName(), userInfo.getId(), userInfo.getOfficeId());
        this.addMessagecenter(gzObj.getId(), ajbh, managerId, deptId, jdToken, jclb, userInfo.getRealName(), xm, bm, sdf.format(date), cfqx, "P", "J", gzObj.getCfbm(), gzObj.getName(), "否");
    }

    @Override
    public LinkedHashMap addZrrGlcf(Removal removal, String xm, String zjtype, String idcard, String position, String cfqx, String frajbh, Date date, long managerId, long deptId, String ysajh, String jdToken, SysUser userInfo, GzObj gzObj) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, String> zrrInfo = lhjcAjbhDao.getZrrInfo(idcard);

        LinkedHashMap linkedHashMap=new LinkedHashMap();

        String tybm = "";

        //不存在的企业录入到自然人库
        if (zrrInfo == null || zrrInfo.get("tybm") == null || zrrInfo.get("tybm").equals("")) {
            tybm = UuidUtil.getInstance().getUUid();
            lhjcAjbhDao.addPerson(tybm, xm, idcard, position, zjtype);
        } else {
            tybm = zrrInfo.get("tybm");

            if (!xm.equals(zrrInfo.get("name"))) {
                linkedHashMap.put("flag","false");
                linkedHashMap.put("errLog","该姓名与库中不一致");
                return linkedHashMap;
            }
        }

        String ajbh = this.getAjbh(removal.getDeptCode(), date);
        lhjcAjbhDao.addMess(tybm, "Y", cfqx, "P", "C", ajbh, removal.getGzId(), removal.getGzmc(), sdf.format(date), xm, frajbh, idcard, "M", managerId, deptId, ysajh, sdf.format(date));
        syslogDao.addProcess(ajbh, "AC", "Y", userInfo.getUsername(), userInfo.getRealName(), userInfo.getId(), userInfo.getOfficeId());

        String glcf = removal.getGlcf();
        if (glcf == null || glcf.equals("")) {
            glcf = ajbh;
        } else {
            glcf = glcf + "," + ajbh;
        }

        lhjcAjbhDao.modifyFrGlcfAjbh(glcf, frajbh);
        this.addMessagecenter(removal.getGzId(), ajbh, managerId, deptId, jdToken, "C", userInfo.getRealName(), xm, idcard, sdf.format(date), cfqx, "P", "J", gzObj.getCfbm(), gzObj.getName(), "是");

        linkedHashMap.put("flag","true");
        linkedHashMap.put("errLog","录入成功");
        return linkedHashMap;
    }

    //获得事件编号
    private String getAjbh(String deptCode, Date date) {
        //八位流水号
        String ajbh = "";
        SimpleDateFormat timestamp = new SimpleDateFormat("yyyyMMdd");

        synchronized (LhjcAjbhServiceImpl.class) {
            Map<String, String> ajbhRecord = lhjcAjbhDao.selectAjbhRecord("ajbh");

            if (!ajbhRecord.get("datetime").equals(timestamp.format(date))) {
                lhjcAjbhDao.modifyAjbhRecord(ajbhRecord.get("id"), timestamp.format(date), 1);
                ajbhRecord.put("datetime", timestamp.format(date));
                ajbhRecord.put("count", 1 + "");
            } else {
                int realCount = Integer.parseInt(ajbhRecord.get("count")) + 1;
                lhjcAjbhDao.modifyAjbhRecord(ajbhRecord.get("id"), timestamp.format(date), realCount);
                ajbhRecord.put("count", realCount + "");
            }

            //编号生成
            ajbh = deptCode + ajbhRecord.get("datetime");
            for (int i = ((String) ajbhRecord.get("count")).length(); i < 4; i++) {
                ajbh = ajbh + "0";
            }

            ajbh = ajbh + ajbhRecord.get("count");
        }

        return ajbh;
    }

    //向消息中心发消息
    private void addMessagecenter(int gzId, String ajbh, long operatorId, long operatorDeptId, String jdToken, String jclb, String operatorName, String ztmc, String bm, String sxsj, String jzrq, String type, String status, String deptName, String gzmc, String glcf) {
        Integer mbId = null;

        if (jclb.equals("C")) {
            mbId = lhjcAjbhDao.selectMbId("C");
        } else {
            mbId = lhjcAjbhDao.selectMbId("G");
        }

        if (null == mbId) {
            return;
        }

        List<Long> list = lhjcAjbhDao.selectDeptIdList(gzId);
        HashSet<Long> h = new HashSet<Long>(list);
        list.clear();
        list.addAll(h);
        HashSet<Long> managerIdList = new HashSet<Long>();

        if (list.contains(-1L)) {
            List<MsgContentEntity> msgContentEntityList = new ArrayList<MsgContentEntity>();
            List<Long> allTopDeptIdList = officeDao.selectAllTopDeptId();
            for (Long id : allTopDeptIdList) {
                List<Long> topAndDownwardIdList = officeDao.selectTopAndDownwardId(id);

                List<Long> managerList = lhjcRemoteBaseService.getDeptManager(StringUtils.join(topAndDownwardIdList, ","), jdToken);

                if (managerList == null || managerList.size() == 0) {
                    continue;
                }

                managerIdList.addAll(managerList);
            }

            if (managerIdList.size() != 0) {
                MsgContentEntity msgContentEntity = new MsgContentEntity();
                if (jclb.equals("C")) {
                    msgContentEntity.setMsgTitle("联合惩戒发起");
                    msgContentEntity.setMsgTypeS("C");
                } else {
                    msgContentEntity.setMsgTitle("联合激励发起");
                    msgContentEntity.setMsgTypeS("G");
                }

                msgContentEntity.setMsgContent(this.getContent(syslogDao.selectMbInfo(mbId), ajbh, operatorDeptId, ztmc, bm, sxsj, jzrq, jclb, type, status, deptName, gzmc, glcf));
                msgContentEntity.setMsgType(4);
                msgContentEntity.setSendId(operatorId);
                msgContentEntity.setSendName(operatorName);

                List<MsgDetailEntity> msgDetailEntityList = new ArrayList<MsgDetailEntity>();

                for (Long managerId : managerIdList) {
                    MsgDetailEntity msgDetailEntity = new MsgDetailEntity();
                    msgDetailEntity.setReviever(managerId);
                    msgDetailEntity.setRevieveType(1);
                    msgDetailEntityList.add(msgDetailEntity);
                }

                msgContentEntity.setDetails(msgDetailEntityList);
                msgContentEntityList.add(msgContentEntity);
            }

            lhjcRemoteBaseService.sendMsg(msgContentEntityList, jdToken);
        } else {
            List<MsgContentEntity> msgContentEntityList = new ArrayList<MsgContentEntity>();

            for (Long id : list
                    ) {
                List<Long> topAndDownwardIdList = officeDao.selectTopAndDownwardId(id);
                List<Long> managerList = lhjcRemoteBaseService.getDeptManager(StringUtils.join(topAndDownwardIdList, ","), jdToken);

                if (managerList == null || managerList.size() == 0) {
                    continue;
                }

                managerIdList.addAll(managerList);
            }

            if (managerIdList.size() != 0) {
                MsgContentEntity msgContentEntity = new MsgContentEntity();
                if (jclb.equals("C")) {
                    msgContentEntity.setMsgTitle("联合惩戒发起");
                    msgContentEntity.setMsgTypeS("C");
                } else {
                    msgContentEntity.setMsgTitle("联合激励发起");
                    msgContentEntity.setMsgTypeS("G");
                }

                msgContentEntity.setMsgContent(this.getContent(syslogDao.selectMbInfo(mbId), ajbh, operatorDeptId, ztmc, bm, sxsj, jzrq, jclb, type, status, deptName, gzmc, glcf));
                msgContentEntity.setMsgType(4);
                msgContentEntity.setSendId(operatorId);
                msgContentEntity.setSendName(operatorName);

                List<MsgDetailEntity> msgDetailEntityList = new ArrayList<MsgDetailEntity>();

                for (Long managerId : managerIdList) {
                    MsgDetailEntity msgDetailEntity = new MsgDetailEntity();
                    msgDetailEntity.setReviever(managerId);
                    msgDetailEntity.setRevieveType(1);
                    msgDetailEntityList.add(msgDetailEntity);
                }

                msgContentEntity.setDetails(msgDetailEntityList);
                msgContentEntityList.add(msgContentEntity);
            }

            lhjcRemoteBaseService.sendMsg(msgContentEntityList, jdToken);
        }
    }

    private String getContent(Template template, String ajbh, long deptId, String ztmc, String bm, String sxsj, String jzrq, String jclb, String type, String status, String deptName, String gzmc, String glcf) {
        List<String> list = new ArrayList<String>();
        Map<String, Object> map = new HashMap<String, Object>();

        String content = "";
        String content1 = "";
        String aString2 = "";
        if (template != null) {
            content = template.getContent();
            content1 = template.getContent();
            String rgex = "(?<=\\{\\{)(.*?)(?=\\}\\})";
            Pattern p = Pattern.compile(rgex);
            Matcher m = p.matcher(content);
            while (m.find()) {
                list.add(m.group());
            }
        }

        boolean flag;

        if (type.equals("C")) {
            type = "法人";
        } else {
            type = "自然人";
        }

        if (jclb.equals("C")) {
            jclb = "联合惩戒";
        } else {
            jclb = "联合激励";
        }

        status = "发起通报";

        map.put("实施期限", jzrq);
        map.put("事件编号", ajbh);
        map.put("主体名称", ztmc);
        map.put("统一社会信用代码或身份证编码", bm);
        map.put("生效时间", sxsj);
        map.put("主体类别", type);
        map.put("发起部门", deptName);
        map.put("事件类别", jclb);
        map.put("是否关联处罚", glcf);
        map.put("规则名称", gzmc);
        map.put("事件状态", status);

        List<String> currentdeptCsList = syslogDao.selectCurrentdeptCs(ajbh, deptId);
        StringBuilder cs = new StringBuilder();
        cs.append("<br/>");
        for (int i = 0; i < currentdeptCsList.size(); i++) {
            cs.append(i + 1).append(".").append(currentdeptCsList.get(i)).append("。").append("<br/>");
        }
        map.put("措施", cs.toString());

        for (String in : map.keySet()) {
            //map.keySet()返回的是所有key的值
            Object str11 = new StringBuffer();
            str11 = map.get(in);//得到每个key多对用value的值
            String aString = "{{" + in + "}}";
            if (str11 == null) {
                aString2 = content1.replace(aString, "");
                content1 = aString2;
            } else {
                aString2 = content1.replace(aString, str11.toString());
                content1 = aString2;
            }

        }

        return content1;
    }

    @Override
    public void addAjfqErrLog(String recordId, String tableName, String errLog) {
        lhjcAjbhDao.addAjfqErrLog(recordId, tableName, errLog);
    }

    @Override
    public LinkedHashMap selectAjfqErrInfo(String recordId, String tableName) {
        return lhjcAjbhDao.selectAjfqErrInfo(recordId, tableName);
    }
}
